package cn.edu.bjtu.core;

import java.io.InputStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.ArrayList;

import org.deeplearning4j.util.SerializationUtils;
import org.nd4j.linalg.api.ndarray.INDArray;

/**
 * Created by alex on 17/6/16.
 */
public class TextCategorizationManager extends LoggerSupport implements java.io.Serializable{
    private static final long serialVersionUID = 1808091468086231953L;
    public static final class ClassificationPair {
        private final String cate;
        private final double val;
        public ClassificationPair(String cate,double val) {
            this.cate = cate;
            this.val = val;
        }

        public String toString(){
            return "{label:"+cate+","+"val:"+val+"}";
        }

        public String getLabelName() {
            return cate;
        }
        public double getVal() {
            return val;
        }

    }

    private static TextCategorizationManager inst = null;
    private TextCategorizationManager(){};

    private List<String> labels;

    public synchronized TextCategorizationManager setLabels(List<String> labels){
        this.labels = new ArrayList<String>(labels);
        return this;
    }


    public static synchronized TextCategorizationManager restore(){
        try{
            InputStream in = TextCategorizationManager.class.getResourceAsStream(SparkConfiguration.LABELS);
            TextCategorizationManager tcm = SerializationUtils.<TextCategorizationManager>readObject(in);
            if(inst==null) inst = tcm;
            if(inst.labels == null){
                inst.labels = tcm.labels;
            }
            return inst;
        }catch(Exception e){
            e.printStackTrace();
        }
        return inst;
    }

    public ClassificationPair[] getDesc(INDArray arr){
        ClassificationPair res [] = new ClassificationPair[this.labels.size()];
        for(int i=0;i<res.length;i++){
            res[i] = new ClassificationPair(this.labels.get(i), arr.getDouble(i));
        }
        Arrays.<ClassificationPair>sort(res,new Comparator<ClassificationPair>(){
            public int compare(ClassificationPair x,ClassificationPair y){
                double t = y.val-x.val;
                return t>0?1:(t<0?-1:0);
            }

        });
        return res;
    }
    public boolean checkLabel(String label){
        return this.labels.contains(label);
    }

    public static TextCategorizationManager get(){
        if(inst == null){
            synchronized (TextCategorizationManager.class) {
                if(inst == null){
                    inst =  new TextCategorizationManager();
                }
            }
        }
        return inst;
    }

}
